package com.bookm.service.excel3;

import com.alibaba.fastjson.JSONObject;
import com.bookm.bean.ImportColumnInfo;
import com.bookm.bean.ImportStatusDTO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * 数据处理
 */
public class SheetHandler extends DefaultHandler {
    private SharedStringsTable sst;
    private StylesTable styles;
    private String lastContents;
    private boolean nextIsString;
    private String cellPosition;
    private int cellStyleIndex = -1;
    private LinkedHashMap<String, JSONObject> rowContents = new LinkedHashMap();
    public HashMap<String, ImportColumnInfo> importNeedColumnMap = new HashMap<>();
    private HashMap<String, String> columnMap = new HashMap<>();
    private DataFormatter dataFormatter = new DataFormatter();
    protected ImportStatusDTO imp_status = new ImportStatusDTO();

    public SheetHandler(SharedStringsTable sst, StylesTable styles) {
        this.sst = sst;
        this.styles = styles;
    }

    public LinkedHashMap<String, JSONObject> getRowContents() {
        return rowContents;
    }

    public void setRowContents(LinkedHashMap<String, JSONObject> rowContents) {
        this.rowContents = rowContents;
    }

    public SheetHandler(SharedStringsTable sst) {
        this.sst = sst;
    }
    // 其他方法如setImportColumn、isExistProperty、isExistColumn保持不变

    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
        if (name.equals("c")) {
            cellPosition = attributes.getValue("r");
            String cellType = attributes.getValue("t");
            String cellStyleStr = attributes.getValue("s");
            //日期类型 cellType=null,cellStyleStr=4
            //文本 数字/浮点类型 cellType=s，cellStyleStr=1
            //浮点/数字类型 cellType=null，cellStyleStr=3
            //公式类型 cellType=null，cellStyleStr=null
            cellStyleIndex = cellStyleStr != null ? Integer.parseInt(cellStyleStr) : -1;
            nextIsString = "s".equals(cellType);
        }
        lastContents = "";
    }

    public void endElement(String uri, String localName, String name) throws SAXException {
        if (name.equals("v")) {
            String value = lastContents.trim();
            if (nextIsString) {
                try {
                    int idx = Integer.parseInt(value);
                    value = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                } catch (NumberFormatException e) {
                    // 保持原值
                }
            } else {
                if (styles != null && cellStyleIndex != -1) {
                    try {
                        CellStyle style = styles.getStyleAt(cellStyleIndex);
                        short formatIndex = style.getDataFormat();
                        String formatString = style.getDataFormatString();
                        double numericValue = Double.parseDouble(value);

                        if (DateUtil.isADateFormat(formatIndex, formatString)) {
                            if (DateUtil.isValidExcelDate(numericValue)) {
                                Date date = DateUtil.getJavaDate(numericValue, false);
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                value = sdf.format(date);
                            }
                        } else {
                            value = dataFormatter.formatRawCellContents(numericValue, formatIndex, formatString);
                        }
                    } catch (NumberFormatException e) {
                        // 非数值，保持原样
                    }
                }
            }

            // 处理列映射和数据存储
            String positionAlpha = cellPosition.replaceAll("[0-9]", "").trim();
            String positionNum = cellPosition.replaceAll("[^0-9]", "").trim();

            if ("1".equals(positionNum)) {
                if (!isExistProperty(value, importNeedColumnMap)) {
                    imp_status.imp_rows_nomatch += value + ",";
                }
                for (String key : importNeedColumnMap.keySet()) {
                    ImportColumnInfo ic = importNeedColumnMap.get(key);
                    if (ic.ici_xls_title.equalsIgnoreCase(value)) {
                        columnMap.put(positionAlpha, ic.ici_column);
                        break;
                    }
                }
            } else if (isExistColumn(positionAlpha, columnMap)) {
                JSONObject rowData = rowContents.getOrDefault(positionNum, new JSONObject());
                rowData.put(columnMap.get(positionAlpha), value);
                rowContents.put(positionNum, rowData);
            }
        }
    }

    public void characters(char[] ch, int start, int length) {
        lastContents += new String(ch, start, length);
    }

    /**
     * 当前的列信息，是否在配置表内
     *
     * @param clm
     * @param iciHash
     * @return
     */
    protected boolean isExistColumn(String clm, HashMap<String, String> iciHash) {
        return iciHash.get(clm) == null ? false : true;
    }

    /**
     * 当前的第一行的名称是否在我的配置表里面 name : name
     *
     * @param clm
     * @param iciHash
     * @return
     */
    protected boolean isExistProperty(String clm, HashMap<String, ImportColumnInfo> iciHash) {
        for (String key : iciHash.keySet()) {
            ImportColumnInfo ic = iciHash.get(key);
            if (ic.ici_xls_title.equalsIgnoreCase(clm)) {
                return true;
            }
        }
        return false;
    }

    // todo 为了结合过去的接口 ，创建handler必须实现这个接口

}